import web
from os.path import join, dirname

#
# GLOBALS
#

session = None
page_render = None
render = None
app = None

app_directory = dirname(__file__)
upload_directory = join(dirname(__file__), "static/uploads")

url_mapping = (
        '/', 'index',
        '/login', 'login',
        '/home', 'home',
        '/test', 'test',
        '/device_info', 'device_info',
        '/admin', 'devices',
        '/admin/keros', 'config_dev_keros',
        '/admin/camera','camera',
        '/measurements', 'measurements',
        '/upload', 'upload',
        '/command', 'command',
        )

# Basic init

def web_init(fvars):
    global app
    web.config.debug = True
    app = web.application(url_mapping, fvars)

def web_run():
    app.run()
    pass

# Session management

def web_init_session():
    global session, app

    web.config.session_parameters['cookie_name'] = 'rnet_session_id'
    web.config.session_parameters['cookie_domain'] = None
    web.config.session_parameters['timeout'] = 86400, #24 * 60 * 60, # 24 hours   in seconds
    web.config.session_parameters['ignore_expiry'] = True
    web.config.session_parameters['ignore_change_ip'] = False
    web.config.session_parameters['secret_key'] = 'deadbeeftfNoIldA0A0J'
    web.config.session_parameters['expired_message'] = 'Session expired'

    if web.config.get('_session') is None:
        session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'user': None} )
        web.config._session = session
    else:
        session = web.config._session


from web.wsgiserver import CherryPyWSGIServer

def web_session_check():
    global session
    if session.user is None:
        raise web.seeother('/login')

# HTTPS

def web_init_https():
    CherryPyWSGIServer.ssl_certificate = "./certificates/rnet.cert"
    CherryPyWSGIServer.ssl_private_key = "./certificates/rnet.key"

# RENDERERS

def web_init_templates():
    global page_render, render

    template_globals = {
        "type" : type,
        "ctx" : web.ctx,
        "session" : session,
        "server" : Server()
    }

    page_render = web.template.render(join(app_directory, "page_templates/"),base="base",globals=template_globals )
    render = web.template.render(join(app_directory, "templates/"),globals=template_globals)

#
# This class is accessible by our templates
#

class Server:
    def __init__(self):
        self.navbar = [
            ("Home","/home"),
            ("Test","/test"),
            ("Measurements","/measurements"),
            ("Administration","/admin"),
            ("Upload","/upload")
        ]

    def getSitePages(self):
        return self.navbar

    def hasSubPages(self):
        path = web.ctx.get("path",None)
        if path == None:
            return False

        # if path is not in root, then it has siblings
        if path[1:].find("/") != -1:
            return True

        # if path is in root, but have other child pages in url mapping
        # then it's a parent page
        path = path + "/"
        for url in url_mapping:
            if url.find(path) == 0:
                return True
        return False

    def getSubPages(self):
        subpages = []
        path = web.ctx.get("path",None)
        if path == None:
            return subpages

        # get parent name
        parent = path[1:].split("/")[0]
        parent = parent + "/"
        lp = len(parent)

        # search all items that have this parent
        for idx in range(0,len(url_mapping),2):
            url = url_mapping[idx]
            if url[1:lp+1] == parent:
                subpages.append( (url[1:].split("/")[1], url) )

        return subpages


